import React, { Component } from 'react'
import { Card, Breadcrumb, Form, Button, Space, Input, Radio, Upload, Modal, message } from 'antd'
import { Link } from 'react-router-dom'
import ChannelList from 'components/ChannelList'
import ReactQuill from 'react-quill'
import 'react-quill/dist/quill.snow.css'
import { PlusOutlined } from '@ant-design/icons'
import { baseURL } from 'utilis/request'
import { getArticleById, publishArticle, updateArticle } from 'api/article'

class ArticlePublish extends Component {
  state = {
    type: 0,
    fileList: [],
    previewUrl: '',
    previewOpen: false,
    id: this.props.match.params.id,
  }
  formRef = React.createRef()

  render() {
    const { type, fileList, previewUrl, previewOpen, id } = this.state
    console.log(type)
    return (
      <div>
        <Card
          title={
            <Breadcrumb>
              <Breadcrumb.Item>
                <Link to={'/home'}>首页</Link>
              </Breadcrumb.Item>
              <Breadcrumb.Item>{id ? '编辑文章' : '发布文章'}</Breadcrumb.Item>
            </Breadcrumb>
          }
        >
          <Form
            labelCol={{ span: 4 }}
            size='large'
            autoComplete='off'
            validateTrigger={['onBlur', 'onChange']}
            onFinish={this.onFinish}
            initialValues={{ type }}
            ref={this.formRef}
          >
            <Form.Item
              name='title'
              label='标题'
              rules={[{ required: true, message: '标题不能为空' }]}
            >
              <Input
                style={{ width: 400 }}
                placeholder='请输入标题'
              ></Input>
            </Form.Item>
            <Form.Item
              name='channel_id'
              label='频道'
              rules={[{ required: true, message: '频道不能为空' }]}
            >
              <ChannelList></ChannelList>
            </Form.Item>
            <Form.Item
              label='图片'
              name='type'
            >
              <Radio.Group onChange={this.changeImgType}>
                <Radio value={0}>无图</Radio>
                <Radio value={1}>单图</Radio>
                <Radio value={3}>三图</Radio>
              </Radio.Group>
            </Form.Item>

            {type !== 0 && (
              <Form.Item wrapperCol={{ offset: 4 }}>
                <Upload
                  listType='picture-card'
                  fileList={fileList}
                  onChange={this.uploadImage}
                  action={`${baseURL}/upload`}
                  name='image'
                  onPreview={this.onPreview}
                  beforeUpload={this.beforeUpload}
                >
                  {fileList.length < type && <PlusOutlined></PlusOutlined>}
                </Upload>
                <Modal
                  open={previewOpen}
                  title='图片预览'
                  footer={null}
                  onCancel={this.handleCancel}
                >
                  <img
                    alt='example'
                    style={{
                      width: '100%',
                    }}
                    src={previewUrl}
                  />
                </Modal>
              </Form.Item>
            )}

            <Form.Item
              label='内容'
              name='content'
              rules={[{ required: true, message: '内容不能为空' }]}
            >
              <ReactQuill
                theme='snow'
                style={{ maxWidth: 800, height: 250, marginBottom: 50 }}
              />
            </Form.Item>
            <Form.Item
              wrapperCol={{ offset: 4 }}
              style={{ marginTop: 40 }}
            >
              <Space>
                <Button onClick={this.onDraft}>存入草稿</Button>
                <Button
                  type='primary'
                  htmlType='submit'
                >
                  {id ? '编辑文章' : '发布文章'}
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </Card>
      </div>
    )
  }

  changeImgType = (e) => {
    this.setState({
      type: e.target.value,
      fileList: [],
    })
  }
  uploadImage = ({ fileList }) => {
    this.setState({
      fileList,
    })
  }
  onPreview = (file) => {
    const url = file.url || file.response.data.url
    this.setState({
      previewOpen: true,
      previewUrl: url,
    })
  }
  handleCancel = () => {
    this.setState({
      previewOpen: false,
      previewUrl: '',
    })
  }
  beforeUpload = (File) => {
    if (File.size > 1024 * 500) {
      message.warn('不能超过500kb')
      return Upload.LIST_IGNORE
    }
    if (!['image/jpeg', 'image/png'].includes(File.type)) {
      message.warn('格式错误')
      return Upload.LIST_IGNORE
    }
    return true
  }

  /**
   存入文章发表或者草稿数据请求
   */
  async onSave(values, draft) {
    const { fileList, type } = this.state
    // 把图片处理成能够请求的格式
    const images = this.state.fileList.map((item) => {
      return item.url || item.response.data.url
    })
    const cover = { type: values.type, images }
    if (fileList.length !== type) {
      return message.warn('图片数量不对')
    }
    if (this.state.id) {
      await updateArticle({ ...values, cover }, draft, this.state.id)
      message.success('编辑成功')
      this.props.history.push('/home/list')
    } else {
      await publishArticle({ ...values, cover }, draft)
      message.success('发布成功')
      this.props.history.push('/home/list')
    }
  }

  onFinish = (values) => {
    this.onSave(values, false)
  }
  onDraft = async () => {
    const values = await this.formRef.current.validateFields()
    this.onSave(values, true)
  }
  async componentDidMount() {
    if (this.state.id) {
      const { data } = await getArticleById(this.state.id)
      const values = { ...data, type: data.cover.type }
      this.formRef.current.setFieldsValue(values)
      const fileList = data.cover.images.map((item) => {
        return { url: item }
      })
      this.setState({
        type: values.type,
        fileList,
      })
    }
  }
}

export default ArticlePublish
